package lcmpt;

import java.io.FileNotFoundException;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;

import org.marc4j.MarcReader;
import org.marc4j.MarcStreamReader;
import org.marc4j.marc.Record;

public class LCMPTReader {

	private TreeMap<String, MyRecord> theRecords;

	public static class MyRecord {
		Record record;
		TreeMap<String, MyRecord> ubb = new TreeMap<String, LCMPTReader.MyRecord>();
	}

	public MutableTreeNode createTreeStructure() throws FileNotFoundException {
		readRecordsIntoMap();
		connectRecords();
		return searchTopLevelsAndMakeJTree();
	}

	private void readRecordsIntoMap() throws FileNotFoundException {
		MarcReader reader = new MarcStreamReader(this.getClass()
				.getResourceAsStream("/docs/LCMPTvocab_140225.mrc"));
		theRecords = new TreeMap<String, LCMPTReader.MyRecord>();
		while (reader.hasNext()) {
			Record record = reader.next();
			String name = MarcUtils.getPreferredName(record);
			MyRecord myRecord = new LCMPTReader.MyRecord();
			myRecord.record = record;
			theRecords.put(name, myRecord);
		}
	}

	private MutableTreeNode searchTopLevelsAndMakeJTree() {
		// Wurzelknoten erstellen
		final DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(
				"LCMPT");
		Set<String> names = theRecords.keySet();
		for (String actualName : names) {
			MyRecord actualRecord = theRecords.get(actualName);
			Record marcRecord = actualRecord.record;
			if (!MarcUtils.hasOB(marcRecord)) {
				rootNode.add(makeJTree(actualName));
			}
		}
		return rootNode;
	}

	private MutableTreeNode makeJTree(String name) {
		final MyTreeNode node = new MyTreeNode(name);
		MyRecord actualRecord = theRecords.get(name);
		Set<String> ubb = actualRecord.ubb.keySet();
		Record marc = actualRecord.record;
		node.dataGerman = "";
		node.dataGerman += MarcUtils.getSynonymsAsHTML(marc);
		node.dataGerman += MarcUtils.getOBBAsHTML(marc);
		node.dataGerman += MarcUtils.getSourcesAsHTML(marc);
		node.dataGerman += MarcUtils.getExplanatoriesAsHTML(marc);
		node.dataGerman += MarcUtils.getTracingNotesAsHTML(marc);
		
		node.marc = MarcUtils.getRecordAsHTML(marc);
				
		int index = 0;
		for (String ub : ubb) {
			node.insert(makeJTree(ub), index);
			index++;
		}
		return node;

	}

	private void connectRecords() {
		Set<String> names = theRecords.keySet();
		for (String actualName : names) {
			MyRecord actualRecord = theRecords.get(actualName);
			Record marcRecord = actualRecord.record;
			List<String> obb = MarcUtils.getOBB(marcRecord);
			for (String ob : obb) {
				MyRecord obR = theRecords.get(ob);
				obR.ubb.put(actualName, actualRecord);
			}
		}
	}

}
